from jira import JIRA
import json
from ApiManager.models import VersionData, Versions


class JiraData():
    """
    jira数据获取
    :param testset_path: dict or list
    :param report_name: str
    :return:
    """
    def __init__(self, version=''):
        jira_URL = 'http://jira.jd.com'
        userName = 'liuyongzhi3'
        password = 'Lyz13478455004)^'
        self.jira = JIRA(basic_auth=(userName, password), options={'server': jira_URL})
        # self.basejql = "project=JDDQ AND issuetype=Bug" + (' AND 版本号=' + version if version and version != '所有版本' else '')
        self.basejql = "project=JDDQ AND issuetype=Bug"
        self.version = version if version else '所有版本'

        self.developerlist = [
            {"name": "李宁", "erp": "lining63"},
            {"name": "李小印", "erp": "lixiaoyin9"},
            {"name": "董建强", "erp": "dongjianqiang3"},
            {"name": "周广超", "erp": "zhouguangchao1"},
            {"name": "刘辉", "erp": "liuhui162"},
            {"name": "刘杨", "erp": "liuyang223"},
            {"name": "刘世娇", "erp": "liushijiao"},
            {"name": "王秀强", "erp": "wangxiuqiang"}
        ]

        self.testerlist = [
            {"name": "刘永志", "erp": "liuyongzhi3"},
            {"name": "宋立辉", "erp": "songlihui"},
            {"name": "孙珠珠", "erp": "sunzhuzhu"},
        ]
        # self.updateAllData()

    def updateAllData(self):
        """
        更新全部数据
        :return dict: None
        """
        self._updateVersionData_Info()
        versions = list(Versions.objects.filter(archived=False).values())
        for ve in versions:
            version = Versions.objects.get(name=ve.get('name'))
            self._updateVersionData_Module(version)
            self._updateVersionData_DevTest(version)
            self._updateVersionData_Attribute(version)
            self._updateVersionData_Function(version)
            self._updateVersionData_Person(version)

    def getVersionData(self):
        """
        jira统计各版本BUG数量
        :return dict: 返回不同维度数据
        """
        vs = Versions.objects.get(name=self.version)
        versions = list(Versions.objects.filter(archived=False).values('name'))
        moduledata = list(VersionData.objects.filter(version=vs, field_type=1).values('field_name', 'totalnum'))
        attributedata = list(VersionData.objects.filter(version=vs, field_type=2).values('field_name', 'totalnum'))
        functiondata = list(VersionData.objects.filter(version=vs, field_type=0).values('field_name', 'totalnum'))
        devtestdata = list(VersionData.objects.filter(version=vs, field_type=3).values('field_name', 'totalnum'))
        versiondata = {
            'versions': versions,
            'moduledata': moduledata,
            'attributedata': attributedata,
            'functiondata': functiondata,
            'devtestdata': devtestdata
        }
        return versiondata

    def getPersonData(self):
        """
        jira统计人员BUG列表数量
        :return dict: 返回不同维度数据
        """
        persondata = {}
        developerdata = []
        testerdata = []
        vs = Versions.objects.get(name=self.version)
        for dev in self.developerlist:
            devdata = {
                'name': dev.get('name'),
                'erp': dev.get('erp'),
                'attributebug': list(VersionData.objects.filter(version=vs, field_type=4, agent_name=dev).values('field_name', 'totalnum'))
            }
            developerdata.append(devdata)

        for te in self.testerlist:
            devdata = {
                'name': te.get('name'),
                'erp': te.get('erp'),
                'attributebug': list(VersionData.objects.filter(version=vs, field_type=5, report_name=te).values('field_name', 'totalnum'))
            }
            testerdata.append(devdata)
        persondata["versions"] = list(Versions.objects.filter(archived=False).values('name'))
        persondata["developerdata"] = developerdata
        persondata["testerdata"] = testerdata
        return persondata

    def _updateVersionData_Info(self):
        """
        更新版本列表
        :return dict: None
        """
        # 更新所有版本数据
        Versions.objects.update_or_create(
            version_id=0,
            defaults={
                'name': '所有版本',
                'description': '所有版本数据',
                'archived': False,
                'functionlist': '打卡 上报 我的店铺 新店铺 销售数据 帮助中心 轨迹 拜访 排行榜 GPS 未注册店铺 资质认证'
            }
        )

        # 更新版本数据
        projects = self.jira.project('JDDQ').raw.get('versions')
        for pro in projects:
            description = pro.get('description') if pro.get('description') else ''
            functionlist = description
            Versions.objects.update_or_create(
                version_id=pro.get('id'),
                defaults={
                    'name': pro.get('name'),
                    'description': description,
                    'archived': pro.get('archived'),
                    'functionlist': functionlist
                }
            )

    def _updateVersionData_Module(self, version):
        """
        更新模块数据
        :return dict: None
        """
        vsname = version.__dict__.get('name')
        jql = self.basejql + (' AND 版本号 = ' + vsname if vsname != '所有版本' else '')
        # 获取模块列表modules
        modules = []
        for mo in self.jira.project('JDDQ').components:
            modules.append(mo.name)
        modules.append('EMPTY')
        # 获取各模块BUG数量
        for module in modules:
            modulejql = jql + " And component = " + module
            VersionData.objects.update_or_create(
                version=version,
                field_type=1,
                field_name=module,
                defaults={
                    'totalnum': self.jira.search_issues(modulejql).__dict__.get('total')
                }
            )

    def _updateVersionData_Attribute(self, version):
        """
        更新jira统计BUG属性
        :return dict: None
        """
        vsname = version.__dict__.get('name')
        jql = self.basejql + (' AND 版本号 = ' + vsname if vsname != '所有版本' else '')
        # 统计BUG类型
        attbug = ["功能遗漏", "程序逻辑错误", "程序校验错误", "界面错误", "用户体验问题/优化提升", "接口问题", "性能问题", "安全问题", "环境问题", "兼容问题"]
        for att in attbug:
            attjql = jql + " AND cf[11400] = " + "\"" + att + "\""  # 转义为了解决/在jql中不兼容的问题
            VersionData.objects.update_or_create(
                version=version,
                field_type=2,
                field_name=att,
                defaults={
                    'totalnum': self.jira.search_issues(attjql).__dict__.get('total')
                }
            )

    def _updateVersionData_DevTest(self, version):
        """
        更新jira统计自测用例BUG
        :return dict: None
        """
        vsname = version.__dict__.get('name')
        jql = self.basejql + (' AND 版本号 = ' + vsname if vsname != '所有版本' else '')
        # 统计开发自测应发现BUG
        dtsql = jql + " AND cf[11405] = 是，在开发自测用例中"  # 转义为了解决/在jql中不兼容的问题
        VersionData.objects.update_or_create(
            version=version,
            field_type=3,
            field_name='自测未通过BUG',
            defaults={
                'totalnum': self.jira.search_issues(dtsql).__dict__.get('total')
            }
        )
        VersionData.objects.update_or_create(
            version=version,
            field_type=3,
            field_name='自测通过BUG',
            defaults={
                'totalnum': self.jira.search_issues(jql).__dict__.get('total') - self.jira.search_issues(dtsql).__dict__.get('total')
            }
        )

    def _updateVersionData_Function(self, version):
        """
        更新jira按功能统计BUG数据
        :return dict: 返回不同属性类别BUG数量
        """
        vsname = version.__dict__.get('name')
        jql = self.basejql + (' AND 版本号 = ' + vsname if vsname != '所有版本' else '')
        # 获取各个功能BUG数量
        funlist = []
        functionlist = version.__dict__.get('functionlist').split(" ")
        for fun in functionlist:
            functionjql = jql + " And text ~ " + fun
            issues = self.jira.search_issues(functionjql)
            for issue in issues:
                funlist.append(issue.raw.get("key"))
            VersionData.objects.update_or_create(
                version=version,
                field_type=0,
                field_name=fun,
                defaults={
                    'totalnum': issues.__dict__.get('total')
                }
            )

        funlist = list(set(funlist))
        VersionData.objects.update_or_create(
            version=version,
            field_type=0,
            field_name='其它',
            defaults={
                'totalnum': self.jira.search_issues(jql).__dict__.get('total') - len(funlist)
            }
        )

    def _updateVersionData_Person(self, version):
        """
        更新jira统计人员BUG列表数量
        :return dict: None
        """
        vsname = version.__dict__.get('name')
        jql = self.basejql + (' AND 版本号 = ' + vsname if vsname != '所有版本' else '')
        for dev in self.developerlist:
            personjql = jql + " And assignee = " + dev.get("erp")
            for data in self._getBugData_Attribute(personjql):
                VersionData.objects.update_or_create(
                    version=version,
                    field_type=4,
                    agent_name=dev,
                    field_name=data.get('name'),
                    defaults={
                        'totalnum': data.get('totalnum')
                    }
                )

        for te in self.testerlist:
            personjql = jql + " And reporter = " + te.get("erp")
            for data in self._getBugData_Attribute(personjql):
                VersionData.objects.update_or_create(
                    version=version,
                    field_type=5,
                    report_name=te,
                    field_name=data.get('name'),
                    defaults={
                        'totalnum': data.get('totalnum')
                    }
                )

    def _getBugData_Attribute(self, jql):
        """
        jira统计BUG属性
        :return dict: 返回不同属性类别BUG数量
        """
        # 统计BUG类型
        attbug = ["功能遗漏", "程序逻辑错误", "程序校验错误", "界面错误", "兼容错误", "用户体验问题/优化提升", "接口问题", "性能问题", "安全问题", "环境问题", "兼容问题"]
        attributedata = []
        for att in attbug:
            attjql = jql + " AND cf[11400] = " + "\"" + att + "\""  # 转义为了解决/在jql中不兼容的问题
            name = att
            totalnum = self.jira.search_issues(attjql).__dict__.get('total')
            attributedata.append({"name": name, "totalnum": totalnum})
        return attributedata


if __name__ == "__main__":
    version = '地勤需求2.9.0'
    starttime = '2018-2-28'
    endtime = '2018-6-12'
    jira = JiraData(version)
    # print(json.dumps(jira.getVersion()))
    print(json.dumps(jira.getVersionData()))
    # print(json.dumps(jira.getPersonData()))
